from torch import nn

class ResNext(nn.Module):
    def __init__(self, block, out_c, classes):
        super().__init__()
        # BottleBlock每次的输入通道
        self.in_channel = 64
        # ------------------------------- #
        # 卷积块1
        # ------------------------------- #
        self.conv1 = nn.Sequential(
            nn.Conv2d(3, 64, kernel_size=7, stride=2, padding=3, bias=False),
            nn.BatchNorm2d(64),
            nn.ReLU(True)
        )
        # ------------------------------- #
        # 最大池化
        # ------------------------------- #
        self.maxpooling = nn.MaxPool2d(3, 2, 1)
        # ------------------------------- #
        # 骨干卷积块
        # ------------------------------- #
        self.conv2 = self.__make_layer(block, out_c[0], 3, 1)
        self.conv3 = self.__make_layer(block, out_c[1], 4, 2)
        self.conv4 = self.__make_layer(block, out_c[2], 6, 2)
        self.conv5 = self.__make_layer(block, out_c[3], 3, 2)

        self.adapt_pooling = nn.AdaptiveAvgPool2d(1)
        self.fc = nn.Linear(2048, classes)
        self.__init_args()

    def __make_layer(self, block, out_c, block_num, init_stride):
        layers = []
        strides = [init_stride] + [1] * (block_num - 1)
        for stride in strides:
            layers.append(block(self.in_channel, out_c, stride))
            self.in_channel = out_c * block.expansion
        return nn.Sequential(*layers)

    def __init_args(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight)
            elif isinstance(m, nn.BatchNorm2d):
                nn.init.constant_(m.weight, 1)
                nn.init.constant_(m.bias, 0)
            elif isinstance(m, nn.Linear):
                nn.init.normal_(m.weight, std=1e-3)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    def forward(self, x):
        out = self.conv1(x)
        out = self.maxpooling(out)
        out = self.conv2(out)
        out = self.conv3(out)
        out = self.conv4(out)
        out = self.conv5(out)
        batch = out.size(0)
        out = self.adapt_pooling(out).view(batch, -1)
        out = self.fc(out)
        return out


class BottleBlock(nn.Module):
    expansion = 2   # 膨胀系数
    def __init__(self, in_c, out_c, stride):
        super().__init__()

        # ------------------------------- #
        # 卷积拓扑结构
        # ------------------------------- #
        self.conv1x1_block = nn.Sequential(
            nn.Conv2d(in_c, out_c, kernel_size=1, stride=1, bias=False),
            nn.BatchNorm2d(out_c),
            nn.ReLU(True)
        )
        self.group_conv = nn.Sequential(
            nn.Conv2d(out_c, out_c, kernel_size=3, stride=stride, padding=1, groups=32, bias=False),
            nn.BatchNorm2d(out_c),
            nn.ReLU(True)
        )
        self.conv1x1_out_block = nn.Sequential(
            nn.Conv2d(out_c, out_c * self.expansion, kernel_size=1, stride=1, bias=False),
            nn.BatchNorm2d(out_c * self.expansion)
        )

        self.relu = nn.ReLU(True)

        self.shotcut = nn.Identity()
        if in_c != out_c * self.expansion:
            self.shotcut = nn.Sequential(
                nn.Conv2d(in_c, out_c * self.expansion, kernel_size=1, stride=stride, bias=False),
                nn.BatchNorm2d(out_c * self.expansion)
            )

    def forward(self, x):
        identify = x
        out = self.conv1x1_block(x)
        out = self.group_conv(out)
        out = self.conv1x1_out_block(out)
        return self.relu(out + self.shotcut(identify))

def resnext50():
    return ResNext(BottleBlock, [128, 256, 512, 1024], 5)

if __name__ == "__main__":
    from utils.utils import get_model_flops_args
    get_model_flops_args(ResNext(BottleBlock, [128, 256, 512, 1024], 5), (3, 224, 224))